package com.example.pt.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.pt.dto.FavoriteDTO;
import com.example.pt.dto.FavoriteRequest;
import com.example.pt.utils.Result;
import com.example.pt.service.FavoriteService;
import com.example.pt.utils.JWTUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 种子收藏控制器
 */
@RestController
@RequestMapping("/favorites")
@CrossOrigin(origins = "*")
public class FavoriteController {

    private static final Logger logger = LoggerFactory.getLogger(FavoriteController.class);

    @Autowired
    private FavoriteService favoriteService;

    /**
     * 获取当前用户收藏列表
     */
    @GetMapping
    public ResponseEntity<Result<List<FavoriteDTO>>> getUserFavorites(@RequestHeader Map<String, String> header) {
        try {
            // 验证Token获取用户ID
            Integer uid = getUserIdFromToken(header);
            if (uid == null || uid == 0) {
                return new ResponseEntity<>(Result.fail("未登录用户无法查看收藏"), HttpStatus.UNAUTHORIZED);
            }
            
            // 获取用户收藏列表
            List<FavoriteDTO> favorites = favoriteService.getUserFavorites(uid);
            
            return new ResponseEntity<>(Result.success(favorites, "获取收藏列表成功"), HttpStatus.OK);
        } catch (Exception e) {
            logger.error("获取收藏列表失败: {}", e.getMessage(), e);
            return new ResponseEntity<>(Result.fail("获取收藏列表失败: " + e.getMessage()), 
                    HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 添加收藏
     */
    @PostMapping
    public ResponseEntity<Result<Boolean>> addFavorite(
            @RequestBody FavoriteRequest request,
            @RequestHeader Map<String, String> header) {
        
        try {
            // 验证参数
            if (request.getTid() == null) {
                return new ResponseEntity<>(Result.fail("种子ID不能为空"), HttpStatus.BAD_REQUEST);
            }
            
            // 验证Token获取用户ID
            Integer uid = getUserIdFromToken(header);
            if (uid == null || uid == 0) {
                return new ResponseEntity<>(Result.fail("未登录用户无法收藏"), HttpStatus.UNAUTHORIZED);
            }
            
            boolean success = favoriteService.addFavorite(uid, request.getTid(), request.getNote());
            
            if (success) {
                return new ResponseEntity<>(Result.success(true, "收藏成功"), HttpStatus.OK);
            } else {
                return new ResponseEntity<>(Result.fail("收藏失败"), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            logger.error("收藏种子失败: {}", e.getMessage(), e);
            return new ResponseEntity<>(Result.fail("收藏失败: " + e.getMessage()), 
                    HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 取消收藏
     */
    @DeleteMapping("/{tid}")
    public ResponseEntity<Result<Boolean>> removeFavorite(
            @PathVariable Integer tid,
            @RequestHeader Map<String, String> header) {
        
        try {
            // 验证Token获取用户ID
            Integer uid = getUserIdFromToken(header);
            if (uid == null || uid == 0) {
                return new ResponseEntity<>(Result.fail("未登录用户无法操作"), HttpStatus.UNAUTHORIZED);
            }
            
            boolean success = favoriteService.removeFavorite(uid, tid);
            
            if (success) {
                return new ResponseEntity<>(Result.success(true, "取消收藏成功"), HttpStatus.OK);
            } else {
                return new ResponseEntity<>(Result.fail("取消收藏失败，可能未收藏该种子"), HttpStatus.BAD_REQUEST);
            }
        } catch (Exception e) {
            logger.error("取消收藏失败: {}", e.getMessage(), e);
            return new ResponseEntity<>(Result.fail("取消收藏失败: " + e.getMessage()), 
                    HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 检查种子是否已收藏
     */
    @GetMapping("/check/{tid}")
    public ResponseEntity<Result<Boolean>> checkFavorite(
            @PathVariable Integer tid,
            @RequestHeader Map<String, String> header) {
        
        try {
            // 验证Token获取用户ID
            Integer uid = getUserIdFromToken(header);
            if (uid == null || uid == 0) {
                return new ResponseEntity<>(Result.success(false, "未登录用户"), HttpStatus.OK);
            }
            
            boolean isFavorited = favoriteService.isFavorited(uid, tid);
            
            return new ResponseEntity<>(Result.success(isFavorited, "检查收藏状态成功"), HttpStatus.OK);
        } catch (Exception e) {
            logger.error("检查收藏状态失败: {}", e.getMessage(), e);
            return new ResponseEntity<>(Result.fail("检查收藏状态失败: " + e.getMessage()), 
                    HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 根据用户ID获取收藏列表
     * @param uid 用户ID
     * @return 收藏列表
     */
    @GetMapping("/user/{uid}")
    public ResponseEntity<Result<List<FavoriteDTO>>> getUserFavoritesByUid(@PathVariable Integer uid) {
        try {
            if (uid == null || uid <= 0) {
                return new ResponseEntity<>(Result.fail("无效的用户ID"), HttpStatus.BAD_REQUEST);
            }
            
            // 获取用户收藏列表
            List<FavoriteDTO> favorites = favoriteService.getUserFavorites(uid);
            
            return new ResponseEntity<>(Result.success(favorites, "获取用户收藏列表成功"), HttpStatus.OK);
        } catch (Exception e) {
            logger.error("获取用户收藏列表失败: {}", e.getMessage(), e);
            return new ResponseEntity<>(Result.fail("获取用户收藏列表失败: " + e.getMessage()), 
                    HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 从请求头中解析用户ID
     */
    private Integer getUserIdFromToken(Map<String, String> header) {
        try {
            // 尝试从两种可能的请求头中获取token
            String token = header.get("token"); // 自定义token头
            
            // 如果没有找到token头，尝试从Authorization头获取
            if ((token == null || token.isEmpty()) && header.containsKey("authorization")) {
                String authHeader = header.get("authorization");
                // 检查是否是Bearer token格式
                if (authHeader != null && authHeader.startsWith("Bearer ")) {
                    // 提取实际的token值(去掉"Bearer "前缀)
                    token = authHeader.substring(7);
                }
            }
            
            if (token != null && !token.isEmpty()) {
                DecodedJWT decodedJWT = JWTUtil.verifyToken(token);
                return decodedJWT.getClaim("uid").asInt();
            }
            
            // 没有有效的token，返回0表示匿名用户
            return 0;
        } catch (Exception e) {
            logger.warn("解析Token失败: {}", e.getMessage());
            return 0;
        }
    }
} 